﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using ClassLib.Classes.Common;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraSplashScreen;
using ISumen;
using Sumen.Business;
using Sumen.Business.Model;
using Sumen.Business.Model.Presenter.Actor;
using Sumen.Business.Model.Presenter.Category;
using Sumen.Business.Model.Presenter.Inventory;
using Sumen.Business.Model.Presenter.Sys;
using Sumen_Stock.LookAndFeel.Sumen_System;
using ClassLib.Sockets;
using Sumen.Business.Model.Presenter.Sales;
using Sumen_Stock.LookAndFeel.Entities;
using System.ComponentModel.Design;
using System.ComponentModel;

namespace Sumen_Stock.LookAndFeel.Sales
{
    public partial class Frm_Sales_Sale : XtraForm
    {
        Frm_Customer_Edit frm_customer_edit;
        private FromCode _fromCode = FromCode.FrmSale;
        private bool isChange = false;
        private customer _cus;
        private string _productDetailsId;
        private bool isOutOfStock = false;

        #region Presenter

        private order _order;
        //private List<orders_details> _ordersDetails;
        InventoryPresenter _inventoryPresenter;
        CustomerPresenter _customerPresenter;
        CustomerTypePresenter _customerTypePresenter;
        OrdersPresenter _ordersPresenter;
        ProductDetailsPresenter _productDetailPresenter;
        DiscountPresenter _discountPresenter;
        OrderStatusPresenter _orderStatusPresenter;
        private ProductPresenter _productPresenter;
        #endregion


        #region From

        public Frm_Sales_Sale()
        {
            InitializeComponent();
            //_ordersDetails = new List<orders_details>();
            _order = new order();
            _order.orders_details = new List<orders_details>();
            _customerPresenter = new CustomerPresenter();
            _customerTypePresenter = new CustomerTypePresenter();
            _ordersPresenter = new OrdersPresenter();
            _productDetailPresenter = new ProductDetailsPresenter();
            _inventoryPresenter = new InventoryPresenter();
            _orderStatusPresenter = new OrderStatusPresenter();
            _discountPresenter = new DiscountPresenter();
            _productPresenter = new ProductPresenter();

            txtDate.EditValue = DateTime.Now;
            var query = new BindingSource(_order.orders_details, "");
            gridControl1.DataSource = query;
            buttonsArray1.btnXoa.Text = "Đặt lại";


            ClsPublic.serverSocket.ReceivesMsgEvent += new System.EventHandler(this.serverSocket_ReceivesMsgEvent);



        }

        protected override void WndProc(ref Message m)
        {
            //MessageBox.Show(m.Msg+"");
            base.WndProc(ref m);	// pass message on to base form
        }

        public override void Refresh()
        {
            SplashScreenManager.ShowForm(typeof(WaitForm1));
            base.Refresh();
            LoadForm();
            SplashScreenManager.CloseForm();
        }

        private void Frm_Sales_Sale_Load(object sender, EventArgs e)
        {
            LoadForm();
        }

        private void Frm_Sales_Sale_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (isChange)
            {
                if (!ClsMsgBox.XacNhanDongTab())
                {
                    e.Cancel = true;
                    return;
                }
                this.Dispose();
            }
            ClsPublic.serverSocket.ReceivesMsgEvent -= new System.EventHandler(this.serverSocket_ReceivesMsgEvent);
        }

        #endregion


        #region Button Event

        private void buttonsArray1_btnEventAdd_click(object sender, System.EventArgs e)
        {
            if (Validation())
            {

                _order.Ord_Code = txtCodeSales.EditValue + string.Empty;
                _order.Ord_Customer_ID = (string)lookUpCustomer.EditValue;
                _order.Ord_Customer_Name = txtCusName.EditValue + string.Empty;
                _order.Ord_Customer_Contact = txtCusPhone.EditValue + string.Empty;
                _order.Ord_Customer_Address = txtCusAddress.EditValue + string.Empty;
                _order.Ord_Date_Orders = txtDate.DateTime;
                _order.Ord_DiscountRate = Convert.ToInt32(spinDiscount.Value);
                _order.Ord_VAT = 0;
                _order.Ord_Total_Amount = Convert.ToDecimal(txtSummary.EditValue);
                //_order.Ord_Discount = ((_order.Ord_DiscountRate ?? 0) / (decimal)100f * _order.orders_details.Sum(p => p.Ords_Amount)) + (((_order.Ord_VAT) / (decimal)100f) * _order.orders_details.Sum(p => p.Ords_Amount));
                _order.Ord_Discount = 0;
                _order.Ord_Cash = Convert.ToDecimal(txtCash.EditValue);
                _order.Ord_Change = Convert.ToDecimal(txtCharge.EditValue);
                _order.Ord_Deposit = Convert.ToDecimal(txtDeposit.EditValue);
                _order.Ord_Payment_Status = (int?)(lookUpStatus.EditValue);
                _order.Ord_User_ID = ClsPublic.User.User_Username;
                _order.Ord_Description = txtDesc.EditValue + string.Empty;
                _order.Ord_Sorted = long.Parse(_order.Ord_Code.Split('-')[2]);


                if (_order.Ord_Payment_Status == (int)OrdersStatus.Paid && isOutOfStock)
                {
                    SplashScreenManager.ShowForm(typeof(WaitForm1));
                    Frm_Split_Orders splitOrders = new Frm_Split_Orders(_order);
                    SplashScreenManager.CloseForm();
                    splitOrders.ShowDialog();
                    if (splitOrders.IsSuccess)
                    {
                        ResetForm();
                    }
                }
                else
                {
                    SplashScreenManager.ShowForm(typeof(WaitForm1));
                    Frm_Confirm_Sales obj = new Frm_Confirm_Sales(_order, _cus);
                    SplashScreenManager.CloseForm();
                    obj.FormStatus = EnumFormStatus.Add;
                    obj.ShowDialog();
                    if (obj.IsSales)
                    {
                        ResetForm();
                    }
                }
            }
        }

        private void buttonsArray1_btnEventDelete_click(object sender, System.EventArgs e)
        {
            if (ClsMsgBox.XacNhan("Bạn có chắc nạp lại lưới?"))
            {
                ResetForm();
            }
        }

        private void buttonsArray1_btnEventPrint_click(object sender, System.EventArgs e)
        {

        }

        private void buttonsArray1_btnEventClose_click(object sender, System.EventArgs e)
        {
            this.Dispose();
        }

        #endregion


        #region Control Event

        private Frm_Search_Product _frmSearchProduct;

        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (_frmSearchProduct == null || _frmSearchProduct.IsDisposed)
            {
                _frmSearchProduct = new Frm_Search_Product();
                _frmSearchProduct.gridView1.DoubleClick += Frm_Search_Product_gridView1_DoubleClick;
                _frmSearchProduct.ShowDialog();
            }
            else
            {
                _frmSearchProduct.ShowDialog();
            }

        }

        void Frm_Search_Product_gridView1_DoubleClick(object sender, EventArgs e)
        {
            string productDetailsId = _frmSearchProduct.gridView1.GetRowCellDisplayText(_frmSearchProduct.gridView1.FocusedRowHandle, _frmSearchProduct.colProductID);

            txtProductDetailsId.EditValue = productDetailsId;
            _frmSearchProduct.Close();
        }

        private void txtProductDetailsId_EditValueChanged(object sender, EventArgs e)
        {
            if (_productDetailPresenter.CheckValidCodeProductDetails(txtProductDetailsId.EditValue + string.Empty))
            {
                _productDetailsId = txtProductDetailsId.EditValue + string.Empty;
                LoadProduct(txtProductDetailsId.EditValue + string.Empty);
                txtProductDetailsId.EditValue = null;
                this.txtProductDetailsId.Properties.NullText = _productDetailsId;
                //txtProductDetailsId.MaskBox.EditValue = null;
                txtProductDetailsId.Focus();
            }
        }

        private void txtDate_EditValueChanged(object sender, System.EventArgs e)
        {
            LoadCodeSales();
        }

        private void spinDiscount_EditValueChanged(object sender, EventArgs e)
        {
            _order.Ord_DiscountRate = Convert.ToInt32(spinDiscount.EditValue);
            SetCharge();
        }

        private void lookUpCustomer_EditValueChanged(object sender, EventArgs e)
        {
            string sCus = lookUpCustomer.EditValue + string.Empty;
            _cus = _customerPresenter.GetById(sCus);

            if (_cus != null)
            {
                lookupLoaiKH.EditValue = _cus.Cus_CUSTOMER_TYPE_ID;
                txtCusPhone.EditValue = _cus.Cus_Phone;
                txtCusName.EditValue = _cus.Cus_FullName;
                txtCusAddress.EditValue = _cus.Cus_Address;
                txtFacebook.EditValue = _cus.Cus_Facebook;
                discount discount = _discountPresenter.GetByCustomerType(_cus.Cus_CUSTOMER_TYPE_ID);
                if (discount != null && discount.Disc_Actived == 1)
                    spinDiscount.EditValue = discount.Disc_Percent + string.Empty;
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (_productDetailPresenter.CheckValidCodeProductDetails(_productDetailsId + string.Empty))
            {
                AutoAddProductDetails();
            }
        }

        private void txtCash_EditValueChanged(object sender, EventArgs e)
        {
            _order.Ord_Cash = Convert.ToInt32(txtCash.EditValue);
            SetCharge();
        }

        private void txtDeposit_EditValueChanged(object sender, EventArgs e)
        {
            _order.Ord_Deposit = Convert.ToInt32(txtDeposit.EditValue);
            SetCharge();
        }

        private void txtSummary_EditValueChanged(object sender, EventArgs e)
        {
            SetCharge();
        }

        private void lookUpStatus_EditValueChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(lookUpStatus.EditValue + string.Empty) && (int)lookUpStatus.EditValue == (int)OrdersStatus.Paid)
            {
                txtCash.Properties.ReadOnly = false;
            }
            else
            {
                txtCash.Properties.ReadOnly = true;
                txtCash.EditValue = 0;
            }
            _order.Ord_Payment_Status = (int)lookUpStatus.EditValue;
        }

        private void lookUpCustomer_Properties_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == ButtonPredefines.Plus)
            {
                if (frm_customer_edit == null)
                {
                    frm_customer_edit = new Frm_Customer_Edit();
                    frm_customer_edit.EnumFormStatus = EnumFormStatus.Add;
                    frm_customer_edit.ShowDialog();
                }
                else
                {
                    frm_customer_edit.EnumFormStatus = EnumFormStatus.Add;
                    frm_customer_edit.ShowDialog();
                }
                LoadCustomer();
                if (frm_customer_edit.Customer != null)
                {
                    lookUpCustomer.EditValue = frm_customer_edit.Customer.Cus_Username;
                }

            }

        }

        #endregion


        #region Grid Event

        private void gridControl1_KeyDown(object sender, KeyEventArgs e)
        {
            int row = gridView1.FocusedRowHandle;
            if ((e.KeyCode == Keys.Delete))
            {
                if (ClsMsgBox.XacNhanXoaThongTin())
                {
                    gridView1.DeleteRow(row);
                    //check san pham co fai la hàng hết không--> enable lookup status
                    var query = from p in _order.orders_details
                                where p.Ords_Quantity > Convert.ToInt32(p.Ords_Temp)
                                select p;
                    if (query.Any())
                    {
                        //lookUpStatus.EditValue = (int)OrdersStatus.OrderOutOfStock;
                        isOutOfStock = true;
                        //lookUpStatus.Properties.ReadOnly = true;
                    }
                    else
                    {
                        isOutOfStock = false;
                        //lookUpStatus.EditValue = (int)OrdersStatus.None;
                        //lookUpStatus.Properties.ReadOnly = false;
                    }
                    //SetSummaryText();
                    SetCharge();
                    isChange = true;
                }
            }
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            isChange = true;
            // SetSummaryText();
            SetCharge();
            if (gridView1.UpdateCurrentRow())
            {
                gridView1.UpdateTotalSummary();
            }
        }

        private void gridView1_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
        }

        private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            int iRow = gridView1.FocusedRowHandle;


            string sDiscount = gridView1.GetRowCellValue(iRow, colDiscount) + string.Empty;
            string sQuantity = gridView1.GetRowCellValue(iRow, colQuantity) + string.Empty;
            string sPrice = gridView1.GetRowCellValue(iRow, colPriceUnit) + string.Empty;

            ////////////////////////////////////////////////////////////////////////////
            if (string.IsNullOrEmpty(sPrice) || sPrice == "0")
            {
                gridView1.SetColumnError(colPriceUnit, string.Format("Bạn chưa nhập giá sản phẩm! ESC để bỏ qua."));
                e.Valid = false;
            }
            ////////////////////////////////////////////////////////////////////////////
            if (string.IsNullOrEmpty(sQuantity) || sQuantity == "0")
            {
                gridView1.SetColumnError(colQuantity, string.Format("Bạn chưa nhập số lượng sản phẩm! ESC để bỏ qua."));
                e.Valid = false;
            }
            ////////////////////////////////////////////////////////////////////////////
            if (string.IsNullOrEmpty(sDiscount))
            {
                gridView1.SetColumnError(colDiscount, string.Format("Bạn chưa nhập giảm giá! ESC để bỏ qua."));
                e.Valid = false;
            }
        }

        private void gridView1_RowStyle(object sender, RowStyleEventArgs e)
        {
            GridView View = sender as GridView;
            if (e.RowHandle >= 0)
            {
                int quantityStock = Convert.ToInt32(View.GetRowCellValue(e.RowHandle, colOutOfStock));
                int quanitity = Convert.ToInt32(View.GetRowCellValue(e.RowHandle, colQuantity));
                if (quantityStock < quanitity)
                {
                    e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Strikeout);
                }
                else
                {
                    e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Regular);
                }
                //check san pham co fai la hàng hết không--> enable lookup status
                var query = from p in _order.orders_details
                            where p.Ords_Quantity > Convert.ToInt32(p.Ords_Temp)
                            select p;
                if (query.Any())
                {
                    //lookUpStatus.EditValue = (int)OrdersStatus.OrderOutOfStock;
                    isOutOfStock = true;
                    //lookUpStatus.Properties.ReadOnly = true;
                }
                else
                {
                    isOutOfStock = false;
                    //lookUpStatus.EditValue = null;
                    //lookUpStatus.Properties.ReadOnly = false;
                }
            }
        }




        #endregion


        #region Method

        void LoadForm()
        {
            LoadCustomer();
            LoadCodeSales();
            LoadOrderStatus();
        }

        void LoadOrderStatus()
        {
            lookUpStatus.Properties.DataSource = _orderStatusPresenter.GetListOrderStatus();
        }

        void LoadCustomer()
        {
            LoadCustomerType();
            lookUpCustomer.Properties.DataSource = _customerPresenter.GetByKey(1);
        }

        void LoadCustomerType()
        {
            lookupLoaiKH.Properties.DataSource = LookUpCusType.DataSource = _customerTypePresenter.GetAll();
        }

        void LoadCodeSales()
        {
            txtCodeSales.EditValue = _ordersPresenter.GetNewCodeOrders(txtDate.EditValue);
        }

        void AutoAddProductDetails()
        {
            orders_details ordersDetails = _order.orders_details.FirstOrDefault(p => p.Ords_PRODUCT_DETAILS_ID == _productDetailsId + string.Empty);
            //add
            if (ordersDetails == null)
            {
                ordersDetails = new orders_details();
                ordersDetails.Ords_PRODUCT_DETAILS_ID = _productDetailsId + string.Empty;
                ordersDetails.Ords_Product_Name = txtProductName.EditValue.ToString();
                ordersDetails.Ords_Discount = (decimal?)(txtDiscount.EditValue) ?? 0;
                ordersDetails.Ords_Quantity = Convert.ToInt32(txtQuantity.EditValue);
                ordersDetails.Ords_Temp = _inventoryPresenter.GetQuantityByProductDetailsId(_productDetailsId + string.Empty).ToString();
                if (_cus == null)
                {
                    ordersDetails.Ords_UnitPrice = Convert.ToDecimal(txtSalePrice.EditValue);
                    ordersDetails.Ords_Amount = ordersDetails.Ords_UnitPrice * ordersDetails.Ords_Quantity;
                }
                else if (_cus.customer_type.CusT_PriceTypeId == (int)PriceType.SalePrice)
                {
                    ordersDetails.Ords_UnitPrice = Convert.ToDecimal(txtSalePrice.EditValue);
                    ordersDetails.Ords_Amount = ordersDetails.Ords_UnitPrice * ordersDetails.Ords_Quantity;
                }
                else if (_cus.customer_type.CusT_PriceTypeId == (int)PriceType.RetailsPrice)
                {
                    ordersDetails.Ords_UnitPrice = Convert.ToDecimal(txtRetailPrice.EditValue);
                    ordersDetails.Ords_Amount = ordersDetails.Ords_UnitPrice * ordersDetails.Ords_Quantity;
                }
                else if (_cus.customer_type.CusT_PriceTypeId == (int)PriceType.AgentPrice)
                {
                    ordersDetails.Ords_UnitPrice = Convert.ToDecimal(txtAgentPrice.EditValue);
                    ordersDetails.Ords_Amount = ordersDetails.Ords_UnitPrice * ordersDetails.Ords_Quantity;
                }

                _order.orders_details.Add(ordersDetails);
                gridView1.RefreshData();
                SetCharge();
            }
            //plus quantity
            else
            {
                ordersDetails.Ords_Quantity++;
                ordersDetails.Ords_Amount = (ordersDetails.Ords_UnitPrice * ordersDetails.Ords_Quantity) -
                                            ordersDetails.Ords_Discount;
                gridView1.RefreshData();
                SetCharge();
            }
            gridView1.FocusedRowHandle = _order.orders_details.Count - 1;
            if (ordersDetails.Ords_Quantity > Convert.ToInt32(txtQuantityStock.EditValue))
            {
                isOutOfStock = true;
            }
        }

        void LoadProduct(string pProductDetailId)
        {
            var invent = _inventoryPresenter.GetByProductDetailsId(pProductDetailId);
            if (invent.Count != 0)
            {
                _productDetailsId = invent.First().product_details.Prods_ID;
                txtProductName.EditValue = invent.First().product_details.product.Prod_Product_Name;
                txtColor.EditValue = invent.First().product_details.product_color.Color_Name;
                txtSize.EditValue = invent.First().product_details.product_size.Size_Name;
                txtSalePrice.EditValue = invent.First().Inv_Sale_Price;
                txtAgentPrice.EditValue = invent.First().Inv_Agent_Price;
                txtRetailPrice.EditValue = invent.First().Inv_Retails_Price;
                txtDiscount.EditValue = invent.First().product_details.product.Prod_Discount ?? 0;
                txtQuantity.EditValue = 1;
                txtQuantityStock.EditValue = invent.Sum(p => p.Inv_Quantity);
                picProduct.EditValue =
                    _productPresenter.GetPicture(_productPresenter.UrlDesImage, invent.First().product_details.product.Prod_Product_ID, invent.First().product_details.product.Prod_Image);
                if (chkAutoAdd.Checked)
                {
                    AutoAddProductDetails();
                }
            }
            else
            {
                var productDetails = _productDetailPresenter.GetById(pProductDetailId);
                if (productDetails != null)
                {
                    _productDetailsId = productDetails.Prods_ID;
                    txtProductName.EditValue = productDetails.product.Prod_Product_Name;
                    txtColor.EditValue = productDetails.product_color.Color_Name;
                    txtSize.EditValue = productDetails.product_size.Size_Name;
                    txtSalePrice.EditValue = productDetails.product.Prod_Sale_Price;
                    txtAgentPrice.EditValue = productDetails.product.Prod_Agent_Price;
                    txtRetailPrice.EditValue = productDetails.product.Prod_Retails_Price;
                    txtDiscount.EditValue = productDetails.product.Prod_Discount ?? 0;
                    txtQuantity.EditValue = 1;
                    txtQuantityStock.EditValue = 0;
                    picProduct.EditValue =
                    _productPresenter.GetPicture(_productPresenter.UrlDesImage, productDetails.product.Prod_Product_ID, productDetails.product.Prod_Image);
                    if (chkAutoAdd.Checked)
                    {
                        AutoAddProductDetails();
                    }
                }
            }
        }

        void ResetForm()
        {
            isChange = false;
            isOutOfStock = false;
            lookUpCustomer.EditValue = null;
            txtCusName.EditValue = null;
            txtFacebook.EditValue = null;
            txtCusPhone.EditValue = null;
            txtCusAddress.EditValue = null;
            txtProductDetailsId.EditValue = null;
            txtSummary.EditValue = 0;
            txtCash.EditValue = 0;
            txtCharge.EditValue = 0;
            txtDeposit.EditValue = 0;
            spinDiscount.EditValue = 0;
            gridControl1.DataSource = null;
            _order.orders_details.Clear();
            var query = new BindingSource(_order.orders_details, "");
            gridControl1.DataSource = query;
            Refresh();
        }

        bool Validation()
        {
            //kiem tra vi tri trong con trong' khong
            dxErrorProvider1.ClearErrors();

            if (lookUpCustomer.EditValue == null || lookUpCustomer.EditValue == "")
            {
                dxErrorProvider1.SetError(lookUpCustomer, "Vui lòng nhập");
                return false;
            }
            else if (txtCusName.EditValue == null || txtCusName.EditValue == "")
            {
                dxErrorProvider1.SetError(txtCusName, "Vui lòng nhập");
                return false;
            }
            else if (txtCusPhone.EditValue == null || txtCusPhone.EditValue == "")
            {
                dxErrorProvider1.SetError(txtCusPhone, "Vui lòng nhập");
                return false;
            }
            else if (lookUpStatus.EditValue == null || lookUpStatus.EditValue == "")
            {
                dxErrorProvider1.SetError(lookUpStatus, "Vui lòng nhập");
                return false;
            }

            if (_order.orders_details.Count == 0)
            {
                ClsMsgBox.ThongTin("Vui lòng nhập sản phẩm");
                return false;
            }
            if (lookUpStatus.EditValue.Equals((int)OrdersStatus.Paid))
            {
                if (!isOutOfStock)
                {
                    if (txtCash.EditValue == null || txtCash.EditValue.ToString() == "0")
                    {
                        dxErrorProvider1.SetError(txtCash, "Vui lòng nhập");
                        return false;
                    }
                }
            }
            if (lookUpStatus.EditValue.Equals((int)OrdersStatus.Deposit))
            {
                if (txtDeposit.EditValue == null || txtDeposit.EditValue.ToString() == "0")
                {
                    dxErrorProvider1.SetError(txtDeposit, "Vui lòng nhập");
                    return false;
                }
            }
            //kiểm tra có lớn số lượng sp co lon hon trong kho khong
            foreach (var ordersDetailse in _order.orders_details)
            {
                if (_inventoryPresenter.GetByProductDetailsId(ordersDetailse.Ords_PRODUCT_DETAILS_ID).Sum(p => p.Inv_Quantity) < ordersDetailse.Ords_Quantity)
                {
                    isOutOfStock = true;
                    if (ClsMsgBox.XacNhan("Sản phẩm \"" + ordersDetailse.Ords_Product_Name
                                          +
                                          "\" không đủ số lượng trong kho.\nHóa đơn sẽ chuyển sang trạng thái đặt hàng tạm hết."))
                    {
                        lookUpStatus.EditValue = (int)OrdersStatus.OrderOutOfStock;
                        return true;
                    }
                    return false;
                }
            }

            return true;
        }

        void SetCharge()
        {
            txtSummary.EditValue = _order.Ord_Total_Amount;
            if (!string.IsNullOrEmpty(lookUpStatus.EditValue + string.Empty) && (int)lookUpStatus.EditValue == (int)OrdersStatus.Paid)
            {

                txtCharge.EditValue = _order.Ord_Change;
            }
            else
            {
                txtCharge.EditValue = 0;
                txtCash.EditValue = 0;
            }

            gridView1.RefreshData();
            if (gridView1.UpdateCurrentRow())
            {
                gridView1.UpdateTotalSummary();
            }
        }

        void serverSocket_ReceivesMsgEvent(object sender, EventArgs e)
        {
            ServerSocket svSocket = (ServerSocket)sender;
            if (InvokeRequired)
            {
                Invoke(new Action<object, EventArgs>(serverSocket_ReceivesMsgEvent), sender, e);
            }
            else
            {
                Main main = (Main)this.MdiParent;
                if (main != null && main.xtraTabbedMdiManager1.SelectedPage.MdiChild is Frm_Sales_Sale)
                {
                    AcceptMessange(svSocket.MsgReceive);
                }
            }
        }

        private void AcceptMessange(MessageSocket msg)
        {
            bool isProduct = _productDetailPresenter.CheckValidCodeProductDetails(msg.Message);
            bool isCustomer = false;
            //kiem tra ma co fai la khach hang khong
            var listCusType = _customerTypePresenter.GetAll();
            foreach (var customerType in listCusType)
            {
                if (!isProduct && msg.Message.StartsWith(customerType.CusT_Code))
                {
                    isCustomer = true;
                    break;
                }
            }
            //la khach hang
            if (!isProduct && isCustomer)
            {
                _cus = _customerPresenter.GetById(msg.Message);
                lookUpCustomer.EditValue = _cus.Cus_Username;
            }
            else if (isProduct)
            {
                //check msg-->mã sp-->check mã sp có h?p l? k-->check có trong kho k-->ok
                //ClsPublic.serverSocket.ClientSockets[msg.Index].Send("ok");
                //MessageBox.Show(msg.Message);
                LoadProduct(msg.Message);

                ClsPublic.serverSocket.ClientSockets[msg.Index].Send("OK");
            }
        }

        #endregion












    }
}